package com.gy.springboot.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

import com.gy.springboot.entity.Department;
import com.gy.springboot.mapper.DepartmentMapper;

@CacheConfig(cacheNames = "dept")
@Service
public class DepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    /**
     * @author GY
     * @date 2018年10月29日
     * @说明:将缓存的结果进行缓存，以后再要相同的数据，直接从缓存中获取，不用调用方法
     */
    @Cacheable(/*value = "dept",*/ condition = "#id>0", unless = "#result == null"/*, keyGenerator = "myKeyGenerator"*/)
    public Department findDepById(Integer id) {
        System.out.println("查询findDepById....." + id);
        return departmentMapper.getDepById(id);
    }

    /**
     * @author GY
     * @date 2018年10月30日
     * @说明:同步更新缓存
     */
    @CachePut(/*value = "dept",*/ key = "#department.id")
    public Department updateEmp(Department department) {
        departmentMapper.updateDepById(department);
        return department;
    }

    /**
     * @author GY
     * @date 2018年10月30日
     * @说明:清除缓存
     * allEntries = true 指定清除这个缓存中所有的数据
     * beforeInvocation = false 缓存的清除是否在方法之前执行，默认代表是在方法执行之后执行，如果出现异常缓存就不会清除
     * beforeInvocation = true 清除缓存操作是在方法执行之前执行，无论方式是否异常，清除缓存都会操作
     */
    @CacheEvict(/*value = "dept",*/ key = "#id")
    public void deleteDept(Integer id) {
        System.out.println("deleteDept"+id);
        //departmentMapper.deleteDepById(id);
    }

    @Caching(
        cacheable = {@Cacheable(/*value = "dept",*/ key = "#departmentName")},
        // 有cacheput 那么此方法一定会执行，不管有没有departmentName缓存
        put = {
            // 按照id也缓存了，所以按照id再查询，也直接使用缓存数据
            @CachePut(/*value = "dept",*/ key = "#result.id")/*,
            @CachePut(value = "dept", key = "#result.***")*/
        }
    )
    public Department getDeptByDeptName(String departmentName) {
        return departmentMapper.getDepByDeptName(departmentName);
    }

}
